<?php

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once 'upload.inc';
include 'plupload/lib/Converter.php';

$upload_path = trim($_GET['path'], '/'); //trim path
$f = isset($_GET['f']) ? $_GET['f'] : false; //neu la tru se insert vao bang files
$uid = isset($_GET['uid']) ? intval($_GET['uid']) : 0; //user id
$action = isset($_GET['action']) ? $_GET['action'] : '';
$json = new stdClass();

//tao duong dan va file name
$arr = explode('.', $_FILES['file']['name']);
$extension = array_pop($arr);
$filename = implode(' ', $arr);
$filename = Converter::utf8_to_ascii($filename);



$path = time() . '_' . Converter::utf8_to_ascii($filename, '_') . '.' . $extension;

if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path . '/' . $path)) {
    $json->status = 'success';
    $json->filename = $path;
    if($f) {//if upload anh theo dang gallery
        switch($action) { 
            case 'products':
                //upload anh cho san pham URL: http://domain.com/backend/list_pictures/7
                $pid = isset($_GET['pid']) ? intval($_GET['pid']) : 0; //id san pham                
                $info = image_get_info($upload_path . '/' . $path); //lay thong tin file upload
                $params = array(
                    'uid' => $uid,
                    'filename' => $filename,
                    'filepath' => $path,
                    'filemime' => $info['mime_type'],
                    'filesize' => $info['file_size'],
                    'status' => 1,
                    'timestamp' => time(),
                    'pid' => $pid
                );
                $json->imageid = insertPictureForProduct($params);
                break;
        }
    }else {
        switch($action) {
            case 'brand':
                $json->imageid = -1;
                break;
        }
    }
}else {
    $json->status = 'error';
}
$json->uid = $user->uid;
echo json_encode($json);
unset($json);